package com.sudu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sudu.dao.CationDao;
import com.sudu.dao.UserDao;
import com.sudu.domain.Cation;
import com.sudu.domain.Communication;
import com.sudu.service.CationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class CationServiceImpl implements CationService {
    @Autowired
    private CationDao cationDao;
    @Autowired
    private UserDao userDao;

    @Override
    public boolean saveCation(Communication communication) {

        return cationDao.saveCation(communication) > 0;
    }

    @Override
    public boolean saveCationFirst(Communication communication) {

        return cationDao.saveCationFirst(communication) > 0;
    }

    @Override
    public boolean ifConnection(int uid, int tid) {

        Cation cation = cationDao.ifConnection(uid, tid);
        if (cation == null) {
            return true;
        } else {
            return cationDao.deleteConnection(cation.getCationID()) > 0;
        }
    }

    @Override
    public List<Communication> getCommunications(int uid, int tid, int page, int pageSize) {
        List<Communication> communications = cationDao.getCommunications(uid, tid, page, pageSize);
        int index = 0;
        Communication communication;
        while (index < communications.size()) {
            communication = communications.get(index);
            communication.setUsername(userDao.getUsernameByUid(communication.getUserId()));
            communication.setUserImg(userDao.getUserImgByUid(communication.getUserId()));
            index++;
        }
        return communications;
    }

    @Override
    public List<Cation> getTidByUid(int uid) {
        List<Cation> cations = cationDao.getTidByUid(uid);
        if (!cations.isEmpty()) {
            int index = 0;
            Cation cation;
            while (index < cations.size()) {
                cation = cations.get(index);
                cation.setTalkName(userDao.getUsernameByUid(cation.getTalkId()));
                index++;

            }

        } else {
            cations = cationDao.getTalkCation(uid);
            int index = 0;
            Cation cation;
            while (index < cations.size()) {
                cation = cations.get(index);
                cation.setTalkName(userDao.getUsernameByUid(cation.getUserId()));
                cation.setTalkId(cation.getUserId());
                index++;
            }

        }
        return cations;
    }
}
